import { resolve } from "path";
import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import eslintPlugin from "vite-plugin-eslint";
import { ViteEjsPlugin } from "vite-plugin-ejs";

const root = process.cwd();

function pathResolve(dir: string) {
	return resolve(root, ".", dir);
}

// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
	let env = {} as any;
	const isBuild = command === "build";
	if (!isBuild) {
		env = loadEnv(process.argv[3] === "--mode" ? process.argv[4] : process.argv[3], root);
	} else {
		env = loadEnv(mode, root);
	}
	console.log(env.VITE_API_BASE_URL);
	return {
		mode: mode,
		server: {
			host: "127.0.0.1",
			port: 8820,
			open: true,
			cors: true,
			proxy: {
				// 带选项写法
				"/api": {
					target: env.VITE_API_BASE_URL,
					changeOrigin: true,
					rewrite: (path) => path.replace(/^\/api/, ""),
				},
				// 代理 websockets
				"/socket.io": {
					target: "ws://localhost:5174",
					ws: true,
				},
			},
		},
		plugins: [
			vue(),
			eslintPlugin({
				include: ["src/**/*.ts", "src/**/*.vue", "src/*.ts", "src/*.vue"],
			}),
			ViteEjsPlugin({
				title: env.VITE_APP_TITLE,
			}),
		],
		resolve: {
			extensions: [".mjs", ".js", ".ts", ".jsx", ".tsx", ".json", ".less", ".css"],
			alias: [
				{
					find: "@",
					replacement: resolve(__dirname, "./src"),
				},
				{
					find: "@assets",
					replacement: resolve(__dirname, "./src/assets"),
				},
				{
					find: "vue",
					replacement: "vue/dist/vue.esm-bundler.js", // compile template
				},
			],
		},
		css: {
			preprocessorOptions: {
				less: {
					modifyVars: {
						hack: `true; @import (reference) "${resolve("src/assets/styles/breakpoint.less")}";`,
					},
					javascriptEnabled: true,
				},
			},
		},
		build: {
			chunkSizeWarningLimit: 20480,
			reportCompressedSize: false,
			rollupOptions: {
				onwarn: () => {},
				output: {
					chunkFileNames: "static/js/[name]-[hash].js",
					entryFileNames: "static/js/[name]-[hash].js",
					assetFileNames: "static/[ext]/[name]-[hash].[ext]",
				},
			},
			minify: "esbuild",
			outDir: env.VITE_OUT_DIR || "dist",
			assetsDir: "static",
			cssCodeSplit: env.VITE_CSS_CODE_SPLIT || false,
		},
		// vite 配置
		define: {
			__APP_TITLE__: JSON.stringify(env.APP_TITLE),
			__VUE_PROD_HYDRATION_MISMATCH_DETAILS__: "true",
		},
	};
});
